import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';


import * as _ from 'lodash';
import store from '@/store';
import type { StateAll } from '@/store';

//首页
const Home = () => import('@/views/home/Home.vue');
// const User = () => import('@/views/user/User.vue');
// const Role = () => import('@/views/role/Role.vue');
//登录
const Login = () => import('@/views/login/Login.vue');
const Register = () => import('@/views/register/Register.vue');

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: Home,
    children: []
    // ,
    // redirect: '/user',
    // children: [
    //   {
    //     path: 'user',
    //     name: 'user',
    //     component: User
    //   },
    //   {
    //     path: 'role',
    //     name: 'role',
    //     component: Role
    //   }

    // ]
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  }
]
// {
//   path: '/login',
//   name: 'login',
//   component: ()=>import('@/views/login/Login.vue')
// }
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
//router.getRoutes().at(1)?.children.push()

router.beforeEach((to, from, next) => {

  const token = (store.state as StateAll).users.token;
  //刷新页面后，需要重新加载router，这里的3就是上面已经定义好的router的长度
  //如果有变化也相应的要变
  if (token && router.getRoutes().length == 3) {
    const permissions = (store.state as StateAll).users.permission;
    permissions.map((permission) => {
      permission.children?.map((second) => {
        const secondName = second.permissionName;
        const secondRoute = {
          path: secondName,
          name: secondName,
          component: () => import('@/views/' + secondName + '/' + _.upperFirst(secondName) + '.vue')
        };
        router.addRoute('home',
          secondRoute
        );
      })
    });
    next({ path: to.fullPath });
  }

  if (token) {
    if (to.path === '/login') {
      next('/');
    }
    else {
      next();
    }
  }
  else {
    if (to.path === '/login'||to.path === '/register') {
      next();
    }
    else {
      next('/login');
    }

  }
});


export default router
